{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# python生成器"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 生成器(Generators)\n",
    "> 特殊的迭代器, 保存产生迭代元素的动作，而不是所有的迭代元素，更节省内存\n",
    "\n",
    "> 方式一：使用yield关键字的函数\n",
    "\n",
    "> 方式二：生成器表达式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n",
      "True\n",
      "True\n",
      "[1, 2, 3, 1, 2, 3]\n",
      "0\n",
      "2\n",
      "4\n",
      "6\n",
      "8\n",
      "10\n",
      "12\n",
      "14\n",
      "16\n",
      "18\n"
     ]
    }
   ],
   "source": [
    "from inspect import isgeneratorfunction, isgenerator\n",
    "from collections import Iterable, Iterator\n",
    "from types import GeneratorType\n",
    "\n",
    "def gen(x):                     #生成器函数\n",
    "    yield x*2\n",
    "print isgeneratorfunction(gen)  #True\n",
    "\n",
    "g2 = (x*2 for x in range(10))   #生成器表达式\n",
    "print isgenerator(g2)           #True\n",
    "print isinstance(g2, Iterator)  #迭代器\n",
    "print isinstance(g2, GeneratorType) #生成器\n",
    "\n",
    "for i in gen([1,2,3]):\n",
    "    print i\n",
    "\n",
    "for i in g2:\n",
    "    print i"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
